from flask_restful import Resource
from flask import g,request,current_app
from flask_restful import reqparse
from comment.models.bank_card import BankCard
from comment.models.user import User
from comment.models import db
from comment.utils.decorators import login_required


class Card_Resource(Resource):
    '''
    银行卡管理的资源类
    '''
    method_decorators = [login_required]
    def post(self):
        '''
        添加银行卡
        :return:
        '''
        uid=g.user_id
        login_user=User.query.filter(User.id==uid).first()

        rp=reqparse.RequestParser()
        rp.add_argument('holder', required=True)       #账户名字
        rp.add_argument('openingBank', required=True)  # 开户银行
        rp.add_argument('bankBranch', required=True)  # 支行
        rp.add_argument('cityId', required=True)  # 城市id
        rp.add_argument('cardNum', required=True)  # 卡片号码

        args = rp.parse_args()


        holder=args.holder
        opening_Bank = args.openingBank
        bank_Branch = args.bankBranch
        city_Id = args.cityId
        bank_Card_Num = args.cardNum

        #验证银行卡卡号是否唯一
        card_info=BankCard.query.filter(BankCard.bankCardNum==bank_Card_Num).first()
        if card_info:
            return {'message':'银行卡已经存在，请勿重复添加','code':2001}

        #把银行卡数据保存到数据库中
        card=BankCard(bankCardNum=bank_Card_Num,openingBank=opening_Bank,holder=holder,
                      bankBranch=bank_Branch,cityId=city_Id,userId=uid,reservePhone=login_user.phone)

        db.session.add(card)
        db.session.commit()
        return {'msg':'success'}


    def get(self):
        '''
        查询当前登录用户所登录用户的所有银行卡
        :return:
        '''
        uid=g.user_id
        card_list=BankCard.query.filter(BankCard.userId==uid).all()

        from financial.resource.card.serializer import BankCardListSerializer
        if card_list:   #把对象转换成字典数据
            return BankCardListSerializer(card_list).to_dict()
        else:
            return {}

    def delete(self):
        '''
        删除银行卡
        :return:
        '''
        rp=reqparse.RequestParser()
        rp.add_argument('carNum',required=True)
        args=rp.parse_args()
        carNum=args.carNum

        bank_info=BankCard.query.filter(BankCard.bankCardNum==carNum).first()
        if bank_info:
            card_info.delete()
            db.session.commit()
            return {'msg':'success'}
        else:
            return {'code':2001,'message':'no this card'}








